#!/usr/bin/env ruby
#encoding: utf-8

require 'net/http'
require 'yaml'
require "nokogiri"
require './qiushibaike'


user = YAML.load_file(File.join('user.yml'))

cookie = ""

login = URI.parse("http://www.oschina.net/action/api/login_validate")

Net::HTTP.start(login.host, login.port) do |http|
  req = Net::HTTP::Post.new(login.path)
  req.set_form_data({'username'=>user['username'], 'pwd'=>user['pwd'], 'keep_login'=>"1"})
  resp = http.request(req)
  cookie = resp.header['set-cookie']
end


headers = {
  'Cookie' => cookie,
}

page = rand(10)
qiubai = QiuBai.print(page)

pub_tweet = URI.parse("http://www.oschina.net/action/api/tweet_pub")
Net::HTTP.start(pub_tweet.host, pub_tweet.port) do |http|
  req = Net::HTTP::Post.new(pub_tweet.path, headers)
  req.set_form_data({'uid'=>'572806', 'msg'=>qiubai})
  resp =  http.request(req)
  puts Nokogiri::XML(resp.body).xpath('//errorMessage').text
end